package com.hudson.broker.handler.process;

import com.google.gson.reflect.TypeToken;
import com.hudson.broker.handler.Process;
import com.hudson.broker.config.BrokerConfig;
import com.hudson.broker.handler.netty.BrokerHandler;
import com.hudson.broker.utils.NettyUtil;
import com.hudson.codec.domain.RemotingCommand;
import com.hudson.common.domain.meta.TopicQueueMap;
import com.hudson.common.enums.MessageTypeEnum;
import com.hudson.core.json.JSONUtil;
import com.hudson.store.queue.QueueNumUtil;
import com.hudson.store.queue.TopicQueue;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class TopicQueueProcesser implements Process {

    @Override
    public RemotingCommand process(ChannelHandlerContext context, RemotingCommand remotingCommand) {
        List<String> topicList = JSONUtil.fromJson(new String(remotingCommand.getBody(), StandardCharsets.UTF_8), new TypeToken<List<String>>() {
        });


        TopicQueue.addTopicQueue(topicList);
        List<Channel> channelList = BrokerHandler.getChannelList();

        if (!channelList.isEmpty()) {
            for (Channel channel : channelList) {
                NettyUtil.write(channel,
                        RemotingCommand.builder()
                                .type(MessageTypeEnum.QUEUE_MAP.getType())
                                .body(JSONUtil.toJson(new TopicQueueMap(BrokerConfig.BROKER_NAME, QueueNumUtil.getMap())).getBytes(StandardCharsets.UTF_8))
                                .build());
//                        RemotingCommandProto.RemotingCommand.newBuilder()
//                                .setType(MessageTypeEnum.QUEUE_MAP.getType())
//                                .setBody(ByteString.copyFromUtf8(JSONUtil.toJson(new TopicQueueMap(BrokerConfig.BROKER_NAME, QueueNumUtil.getMap()))))
//                                .build());

            }
        }
        return null;
    }
}
